const request = require('request');

function getDateYYYYMMDDHHMMSS() {
    var date_time = new Date();
    var year = date_time.getFullYear();
    var month = date_time.getMonth() + 1;
    if (month < 10) month = '0' + month;

    var day = date_time.getDate();
    if (day < 10) day = '0' + day;

    var hour = (date_time.getHours() < 10) ? ("0" + date_time.getHours()) : date_time.getHours();
    var min = (date_time.getMinutes() < 10) ? ("0" + date_time.getMinutes()) : date_time.getMinutes();
    var sec = (date_time.getSeconds() < 10) ? ("0" + date_time.getSeconds()) : date_time.getSeconds();

    return (year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec);
}
function convertToTree(rows, keyField = 'id', parentKeyField = 'parentId') {
    if (!rows) return [];

    // 拷贝，多次执行修改原始的rows会出问题，指定id，parentId
    // eslint-disable-next-line no-param-reassign
    rows = rows.map(item => ({ id: item[keyField], parentId: item[parentKeyField], ...item }));

    // 获取所有的顶级节点
    let nodes = rows.filter(item => !rows.find(r => r.id === item.parentId));

    // 存放要处理的节点
    let toDo = [...nodes];

    while (toDo.length) {
        // 处理一个，头部弹出一个。
        let node = toDo.shift();
        // 获取子节点。
        rows.forEach(child => {
            if (child.parentId === node.id) {

                if (node.children) {
                    node.children.push(child);
                } else {
                    node.children = [child];
                }
                // child加入toDo，继续处理
                toDo.push(child);
            }
        });
    }
    return nodes;
}
function findGenerationNodes(treeData, fieldValue, field = 'id') {
    const node = findNode(treeData, fieldValue, field);

    if (!node) return [];

    if (!node.children || !node.children.length) return [];

    const results = [];
    const loop = nodes => nodes.forEach(item => {
        results.push(item);
        if (item.children && item.children.length) loop(item.children);
    });

    loop(node.children);

    return results;
}
function findNode(treeData, fieldValue, field = 'id', compare = (a, b, item = {}) => a == b) {
    treeData = Array.isArray(treeData) ? treeData : [treeData];

    if (!treeData || !treeData.length) return null;

    let node = null;
    const loop = (data) => {
        for (let item of data) {
            if (compare(item[field], fieldValue, item)) {
                node = { ...item };
                break;
            }
            if (item.children && item.children.length) {
                loop(item.children);
            }
        }
    };
    loop(treeData);
    return node;
}
function getDateIntSecs() {
    var date = new Date();
    var time = parseInt(date.getTime() / 1000);
    return time;
}

function getRandomInt(len) {
    len = len || 32;
    var $chars = '123456789'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = $chars.length;
    var ret = '';
    for (var i = 0; i < len; i++) {
        ret += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return ret;
}

function sendSMSByAli(tel,code) {  
    console.log('------------------------发送短信-------------------');
    let msg = '您的验证码为:';
    let msg2 = '，请勿泄露于任何人!';
    console.log(encodeURI('http://service2.winic.org/service.asmx/SendMessages?uid=fominfo&pwd=fom12345678&tos=' + tel + '&msg=' + msg + code + msg2 + '&otime='));
    request(encodeURI('http://service2.winic.org/service.asmx/SendMessages?uid=fominfo&pwd=fom12345678&tos=' + tel + '&msg=' + msg + code + msg2 + '&otime='), function (error, response, body) {
        console.log("status: ", body);
        console.log("statusCode: ", body.Code);
        console.log("statusCode: ", body.Message);

    }).on('error', function (e) {
        console.error(e);
    });
}

exports.getDateYYYYMMDDHHMMSS = getDateYYYYMMDDHHMMSS;
exports.convertToTree = convertToTree;
exports.findGenerationNodes = findGenerationNodes;
exports.getDateIntSecs = getDateIntSecs;
exports.getRandomInt = getRandomInt;
exports.sendSMSByAli = sendSMSByAli;